package com.czq.fliter;

import com.alibaba.fastjson.JSON;
import com.czq.common.BaseContext;
import com.czq.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter("/*")
public class LoginCheckFilter  implements Filter {
    public final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response=   (HttpServletResponse) servletResponse;

        String s = request.getRequestURI();
         log.info("拦截到请求："+s);
        String urls[]={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",



                "/user/sendMsg",//移动端发送短信
                "/user/login" //移动端登录

        };

        boolean flag = AntPathMatchers(urls,s);

        if (flag){
            log.info("放行的请求,本次不需要处理："+s);
            filterChain.doFilter(request,response);
            return;
        }

        //判断后端是否登录
        Object employee = request.getSession().getAttribute("employee");
        if (employee!=null){
//            long id = Thread.currentThread().getId();
//            log.info("线程id为：{}",id);
            Long empid=(Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empid);
            log.info("用户已经登录"+request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }


        //判断用户是否短信登录
        Object user = request.getSession().getAttribute("user");
        if (user!=null){

            Long userid=(Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userid);
            log.info("用户已经登录"+request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }


        else {
            log.info("用户未登录：");
            response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
            return;
        }




    }
        public boolean AntPathMatchers(String urls[] ,String s){
        for (  String  url : urls ){
            boolean match = PATH_MATCHER.match(url,s);
            if (match){
                return true;
            }
        }
        return  false;

        }


    }

